#include <QTimer>
#include "FocusMeasureObject.h"

namespace Qly
{
FocusMeasureObject::FocusMeasureObject(QObject *parent)
    : QObject{parent}
{

    m_pTimer = new QTimer(this);
    if(m_pTimer)
    {
        m_pTimer->setTimerType(Qt::CoarseTimer);
        m_pTimer->setSingleShot(true);
        connect(m_pTimer, &QTimer::timeout, this, &FocusMeasureObject::on_timeout);
    }
}

void FocusMeasureObject::setFocusParameter(FocusMeasure::MeasureMethod method, int factor)
{
    m_focusMeasure.setMeasureMethod(method);
    m_focusMeasure.setZoomFactor(factor);
}

void FocusMeasureObject::setInterval( unsigned int ms)
{
    m_interval = ms;
}

void FocusMeasureObject::start(unsigned int ms)
{
    m_interval = ms;
    m_enable = true;
}

void FocusMeasureObject::stop()
{
    if( m_pTimer ) m_pTimer->stop();
    m_enable = false;
}

void FocusMeasureObject::setImage(QImage &colorImage)
{
    if( !m_enable ) return;

    cv::Mat gray = m_focusMeasure.preprocess(colorImage);
    m_score = m_focusMeasure.measure(gray);

    m_enable = false;

    if( m_pTimer ) m_pTimer->start(m_interval);

    emit focusMeasure(colorImage, m_score);
}

void FocusMeasureObject::on_timeout()
{
    m_enable = true;
}

}

